package org.jeecg.modules.unitGroup.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.api.entity.CyEmissionUnit;
import org.jeecg.modules.factor.mapper.CyEmissionUnitMapper;
import org.jeecg.modules.unitGroup.entity.CyFactorUnitGroup;
import org.jeecg.modules.unitGroup.mapper.CyFactorUnitGroupMapper;
import org.jeecg.modules.unitGroup.service.ICyFactorUnitGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 碳排因子单位分组表
 * @Author: jeecg-boot
 * @Date:   2024-11-06
 * @Version: V1.0
 */
@Service
public class CyFactorUnitGroupServiceImpl extends ServiceImpl<CyFactorUnitGroupMapper, CyFactorUnitGroup> implements ICyFactorUnitGroupService {

    @Autowired
    private CyEmissionUnitMapper cyEmissionUnitMapper;

    @Autowired
    private CyFactorUnitGroupMapper cyFactorUnitGroupMapper;

    @Override
    public Result<String> delete(String id) {
        //查询出是否有单位相关联当前要删除的单位分组
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",id);
        Long count = cyEmissionUnitMapper.selectCount(queryWrapper);
        //如果有关联的单位，则不允许删除
        if(count>0){
            return Result.error("有单位关联当前分组，不能删除");
        }else{
            this.baseMapper.deleteById(id);
            return Result.ok("删除成功");
        }
    }

    @Override
    @Transactional
    public void edit(CyFactorUnitGroup cyFactorUnitGroup) {
        this.baseMapper.updateById(cyFactorUnitGroup);
        cyEmissionUnitMapper.updateGroupName(cyFactorUnitGroup.getId(),cyFactorUnitGroup.getGroupName());
    }

    @Override
    public Map<String, List<CyEmissionUnit>> getUnitTree() {

        Map<String, List<CyEmissionUnit>> Unitmap = new HashMap();

        //查询出所有分组
        List<CyFactorUnitGroup> UnitGrouplist =  cyFactorUnitGroupMapper.select();
        //拿出所有分组id
        for (CyFactorUnitGroup cyFactorUnitGroup : UnitGrouplist) {
            //当前分组下所有关联的单位
            List<CyEmissionUnit> cyEmissionUnits = cyEmissionUnitMapper.selectByUnitGroupId(cyFactorUnitGroup.getId());
            Unitmap.put(cyFactorUnitGroup.getGroupName(),cyEmissionUnits);
        }
        return Unitmap;
    }

    @Override
    public List<CyFactorUnitGroup> getAllUnitGroup() {
        List<CyFactorUnitGroup> allUnitGroup =  cyFactorUnitGroupMapper.select();
        return allUnitGroup;
    }
}
